#!/usr/bin/env python
#config.py

"""G-Startup configuration reader/writer

Author: Miroslav Zadravec
Date: 2010-02-06

Contains functions for reading and writing to a G-Startup configuration file.
Configuration directory is named gstart and is created under path read from 
environment variable '$XDG_CONFIG_HOME'.
Configuration file name is 'gstartup.cfg'.

"""

import os
import shlex

from timedef import TimeList, TimeDef

def get_configfilepath():
    """Setup the config file.
    
    Checks if config directory exist and create it if needed.
    """
    
    #read config path from environment variable
    userconfig_home = os.getenv('$XDG_CONFIG_HOME')
    if userconfig_home == None:
        userconfig_home = os.path.expanduser("~/.config")    
    
    #join gstart folder and create it if it doesn't exist
    config_dir = os.path.join(userconfig_home, "gstartup")
    if not os.path.exists(config_dir):
        os.mkdir(config_dir)
    
    return os.path.join(config_dir,"gstartup.cfg")

def read_times():
    """Reads time list from config file
    
    Returns: TimeList object
    """
    
    SECTION_PROGRAM = "PROGRAM"
    SECTION_STARTUP = "STARTUP"
    
    times = TimeList()
    
    configpath = get_configfilepath()
    if not os.path.exists(configpath):
        return times
    
    configfile = open(configpath, 'r')    
    
    cur_section = ""
    
    for line in configfile:
        line = line.strip()
        if line == "":
            #empty line, do nothing
            pass
        elif line.startswith("#"):
            #it's a comment, do nothing
            pass
        elif line.endswith(":"):
            #it's a section header
            cur_section = line[0: len(line)-1]
        else:
            if cur_section == SECTION_PROGRAM:
                pass
            elif cur_section.upper() == SECTION_STARTUP:
                time = line_to_time(line)
                if not time == None:
                    times.push(time)
    return times

def line_to_time(line):
    """Converts a string to a TimeDef object"""
    
    #split string by spaces but ignore spaces within quotes
    values = shlex.split(line)
    
    #valid lines have 3 properties, offset, name and path
    if len(values) == 3:
        offset = values[0]
        name = values[1]
        path = values[2]
        time = TimeDef(name, offset, path)
        return time
    else:
        print "Wrong timedef: " + line

            